﻿using DevExpress.Mvvm;
using DevExpress.Mvvm.Native;
using DevExpress.Utils.About;
using DevExpress.Utils.Svg;
using HandyControl.Controls;
using HandyControl.Data;
using HandyControl.Properties.Langs;
using PlaceOrder_Admin.Events;
using PlaceOrder_Admin.Models.Common;
using PlaceOrder_Core.PlaceOrderModels;
using PlaceOrder_Core.Services.Instances;
using PlaceOrder_Core.Services.Interfaces;
using PlaceOrder_Shared.Models.Chat;
using Prism.DryIoc;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;

namespace PlaceOrder_Admin.ViewModels
{
    /// <summary>
    /// 聊天窗口的ViewModel
    /// </summary>
    /// 
    public class ChatAdminMessageViewModel : BindableBase
    {
        #region 依赖属性

        public ObservableCollection<ChatAdminWindowViewModel> ChatWindows { get; set; }
        private ObservableCollection<ChatBroker> brokerChatList;

        /// <summary>
        /// List绑定对象
        /// </summary>
        public ObservableCollection<ChatBroker> BrokerChatList
        {
            get { return brokerChatList; }
            set { brokerChatList = value; RaisePropertiesChanged(); }
        }

        private ObservableCollection<string> brokerList;

        /// <summary>
        /// 多选绑定对象
        /// </summary>
        public ObservableCollection<string> BrokerList
        {
            get { return brokerList; }
            set { brokerList = value; RaisePropertiesChanged(); }
        }




        private ObservableCollection<ChatMessage> messageDataList;

        public ObservableCollection<ChatMessage> MessageDataList
        {
            get { return messageDataList; }
            set { messageDataList = value; }
        }


        private object subContent;

        public object SubContent
        {
            get { return subContent; }
            set { subContent = value; RaisePropertiesChanged(); }
        }


        private int uniformNumber;

        public int UniformNumber
        {
            get { return uniformNumber; }
            set { uniformNumber = value; RaisePropertiesChanged(); }
        }

        #endregion


        #region 命令
        public DelegateCommand<ChatBroker> NavigateChatWindowCmd => new(RefreshChatBox);


        #endregion
        private readonly ChatAdminWindowViewModel _chatWindowViewModel;

        public ChatAdminMessageViewModel()
        {

        }
        private readonly IDailyData _dailyData;
        public ChatAdminMessageViewModel(ChatAdminWindowViewModel chatWindowViewModel, IDailyData dailyData)
        {
            _dailyData = dailyData;
            InitChatBrokers();
            _chatWindowViewModel = chatWindowViewModel;
            Messenger.Default.Register<List<ChatMessage>>(this, MessageToken.NewChatMessageIn, ReceiveNewBrokerMessages);

            ChatCheckBoxEventService.CheckComboBoxSelectionChanged += OnCheckComboBoxSelectionChanged;
        }

        private async void OnCheckComboBoxSelectionChanged(object? sender, CheckComboBoxSelectionEventArgs e)
        {
            if (e.AddedItems != null)
            {
                foreach (var item in e.AddedItems)
                {
                    // 检查 ChatWindows 是否已经包含这个 ChatAdminWindowViewModel
                    if (ChatWindows.Any(vm => vm.ChatTitle == item))
                    {
                        Growl.WarningGlobal(item + "已经存在");
                    }
                    else
                    {
                        // 模拟异步操作，例如数据库查询
                        await Task.Delay(100); // 异步等待，模拟数据库查询或其他异步操作

                        // 根据选中项添加新的 ChatAdminWindowViewModel 到 ChatWindows
                        ChatWindows.Add(new ChatAdminWindowViewModel(_dailyData, item) { ChatTitle = item });
                        //Growl.InfoGlobal(item + "被选中了");
                    }
                }

                // 处理选中项的逻辑
            }

            if (e.RemovedItems != null)
            {
                foreach (var item in e.RemovedItems)
                {
                    // 查找并移除指定 ChatAdminWindowViewModel
                    var viewModelToRemove = ChatWindows.FirstOrDefault(vm => vm.ChatTitle == item);
                    if (viewModelToRemove != null)
                    {
                        ChatWindows.Remove(viewModelToRemove);
                        //Growl.InfoGlobal(item + "被移除了");
                    }
                }
            }

            if (ChatWindows.Count <= 1)
            {
                UniformNumber = 1;
            }
            else
            {
                UniformNumber = 2;
            }
        }

        private void ReceiveNewBrokerMessages(List<ChatMessage> models)
        {
            if (models.Count > 0)
            {
                var broker = this.BrokerChatList.Where(o => o.BrokerName.Contains(models[0].BrokerName)).FirstOrDefault();
                if (broker == null)
                {
                    Growl.ErrorGlobal("未找到可用中介" + models[0].BrokerName);
                }
                else
                {
                    if (broker.BrokerName != TempBrokerName)//如果不是当前页面
                    {
                        broker.UnreadMessageCount += models.Count;
                    }

                }

            }

        }

        private void InitChatBrokers()
        {
            BrokerChatList = new ObservableCollection<ChatBroker>();
            var filteredBrokerList = IndexAdminViewModel.Receivers
     .Where(broker => broker.Brokerid > 0 && !string.IsNullOrEmpty(broker.Company))
     .Select(broker => new ChatBroker
     {
         BrokerId = (int)broker.Brokerid,
         BrokerName = broker.Company,
         Icon = "\uEB68",
         UnreadMessageCount = 0,
         IsChecked = true
     })
     .ToList();

            // 清空并添加筛选后的Broker到BrokerChatList
            BrokerChatList.Clear();
            foreach (var broker in filteredBrokerList)
            {
                BrokerChatList.Add(broker);
            }
            BrokerList = BrokerChatList.Select(o => o.BrokerName).Distinct().ToList().ToObservableCollection();
            //BrokerChatList.Add(new ChatBroker() { Icon = "\uEB68", UnreadMessageCount = 0, BrokerName = "信唐",BrokerId=1});
            //BrokerChatList.Add(new ChatBroker() { Icon = "\uEB68", UnreadMessageCount = 0, BrokerName = "国利", BrokerId = 2});
            //BrokerChatList.Add(new ChatBroker() { Icon = "\uEB68", UnreadMessageCount = 0, BrokerName = "国际", BrokerId = 3});
            //BrokerChatList.Add(new ChatBroker() { Icon = "\uEB68", UnreadMessageCount = 0, BrokerName = "平安",BrokerId=4 });
            //BrokerChatList.Add(new ChatBroker() { Icon = "\uEB68", UnreadMessageCount = 0, BrokerName = "信唐" });
            //BrokerChatList.Add(new ChatBroker() { Icon = "\uEB68", UnreadMessageCount = 0, BrokerName = "中诚" });

            ChatWindows = new ObservableCollection<ChatAdminWindowViewModel>();
            // Add some initial ChatWindowViewModels for demonstration purposes
            //ChatWindows.Add(new ChatAdminWindowViewModel(_dailyData, "国利") { ChatTitle = "国利" });
            //ChatWindows.Add(new ChatAdminWindowViewModel(_dailyData, "国际") { ChatTitle = "国际" });
            //ChatWindows.Add(new ChatAdminWindowViewModel(_dailyData, "平安") { ChatTitle = "平安" });
            //ChatWindows.Add(new ChatAdminWindowViewModel(_dailyData, "中诚") { ChatTitle = "中诚" });
            //ChatWindows.Add(new ChatAdminWindowViewModel(_dailyData, "信唐") { ChatTitle="信唐" });

        }

        #region 初始化
        private void UpdateMainContent()
        {
            Messenger.Default.Register<object>(this, MessageToken.LoadShowContent, obj =>
            {
                if (SubContent is IDisposable disposable)
                {
                    disposable.Dispose();
                }
                SubContent = obj;
            });
        }

        private void UpdateLeftContent()
        {
            //clear status
            Messenger.Default.Register<object>(this, MessageToken.ClearLeftSelected, obj =>
            {
                //DemoItemCurrent = null;
                //foreach (var item in DemoInfoCollection)
                //{
                //    item.SelectedIndex = -1;
                //}
            });

            Messenger.Default.Register<object>(this, MessageToken.LangUpdated, obj =>
            {
                //if (DemoItemCurrent == null) return;
                //ContentTitle = LangProvider.GetLang(DemoItemCurrent.Name);
            });

            //加载数据
            Task.Factory.StartNew(() =>
                Task.Run(() =>
                {
                    MessageDataList = new ObservableCollection<ChatMessage> { new ChatMessage() };

                    //foreach (var item in _dataService.GetDemoInfo())
                    //{
                    //    PrismApplication.Current.Dispatcher.BeginInvoke(new Action(() =>
                    //    {
                    //        DemoInfoCollection.Add(item);
                    //    }), DispatcherPriority.ApplicationIdle);
                    //}
                }));
        }

        public string TempBrokerName = null;
        /// <summary>
        /// 根据不同中介刷新聊天框
        /// </summary>
        private async void RefreshChatBox(ChatBroker broker)
        {
            string brokerName = broker.BrokerName;
            var broker2 = this.BrokerChatList.Where(o => o.BrokerName.Contains(brokerName)).FirstOrDefault();
            if (broker2 != null)
            {
                broker2.UnreadMessageCount = 0;
            }
            //Messenger.Default.Send<string>(string.Empty, MessageToken.ClearChatWindow);
            //string brokerName = broker.BrokerName;
            //string info1 = brokerName;
            //TempBrokerName = info1;
            //Messenger.Default.Send(info1, MessageToken.SendChatMessage);
            //int brokerId = (int)OrderListViewModel.ChatReceivers.Where(o => o.Company == brokerName).FirstOrDefault().Brokerid;
            //List<ChatMessage> tempMessageList = new List<ChatMessage>();
            //tempMessageList = await Task.Run(() => _dailyData.GetAllMessageDataByBrokerId(brokerId, 0));

            //var broker2 = this.BrokerChatList.Where(o => o.BrokerName.Contains(brokerName)).FirstOrDefault();
            //if(broker2!= null)
            //{
            //    broker2.UnreadMessageCount = 0;
            //}
            //Messenger.Default.Send(tempMessageList, MessageToken.SendChatMessage);
        }


        #endregion
    }
}
